/* eslint-disable */
import React, { useEffect, useState, useCallback } from 'react';
import { Table, Button, Form, Input, message, Card } from 'antd';
import axios from 'axios';
import debounce from 'lodash/debounce';
import ReactECharts from 'echarts-for-react'; // 引入ECharts

const { Item: FormItem } = Form;
const DEBOUNCE_DELAY = 1000; // 1秒防抖延迟

const View_Inf = () => {
    const [assessments, setAssessments] = useState([]);
    const [filteredAssessments, setFilteredAssessments] = useState([]);
    const [statistics, setStatistics] = useState({ levelDistribution: [], operationTimes: [] }); // 存储统计数据
    const [form] = Form.useForm();
    const [searchForm] = Form.useForm();
    const [isSearching, setIsSearching] = useState(false);

    useEffect(() => {
        fetchAssessments();
        fetchStatistics(); // 获取统计数据
    }, []);

    const getToken = () => {
        return localStorage.getItem('token');
    };

    const fetchAssessments = () => {
        axios.get('http://47.111.104.30:8080/api/v2/assessments', {
            headers: {
                'Authorization': `Bearer ${getToken()}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            setAssessments(response.data);
            setFilteredAssessments(response.data);
        })
        .catch(error => {
            console.error('Error fetching assessments:', error);
            message.error('获取评价信息失败！');
        });
    };

    const fetchStatistics = () => {
        axios.get('http://47.111.104.30:8080/api/v2/assessments/statistics', {
            headers: {
                'Authorization': `Bearer ${getToken()}`,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            setStatistics(response.data);
        })
        .catch(error => {
            console.error('Error fetching statistics:', error);
            message.error('获取统计数据失败！');
        });
    };

    // 使用防抖的搜索函数
    const debouncedSearch = useCallback(
        debounce(async (keyword) => {
            if (!keyword || !keyword.trim()) {
                message.error('请输入搜索内容');
                return;
            }

            try {
                const response = await axios.get(`http://47.111.104.30:8080/api/v2/assessments/search?keyword=${keyword}`, {
                    headers: {
                        'Authorization': `Bearer ${getToken()}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.data || response.data.length === 0) {
                    message.error('未找到匹配的数据');
                    // 清空当前数据
                    setFilteredAssessments([]);

                    // 3秒后恢复原有数据
                    setTimeout(() => {
                        setFilteredAssessments(assessments);
                    }, 3000);
                } else {
                    setFilteredAssessments(response.data);
                    message.success('搜索成功！');
                }
            } catch (error) {
                console.error('Error searching assessments:', error);
                message.error('搜索失败！');
                // 清空当前数据
                setFilteredAssessments([]);

                // 3秒后恢复原有数据
                setTimeout(() => {
                    setFilteredAssessments(assessments);
                }, 3000);
            } finally {
                setIsSearching(false);
            }
        }, DEBOUNCE_DELAY),
        [assessments]
    );

    const handleSearch = (values) => {
        const { keyword } = values;

        if (isSearching) {
            message.warning('您点击太快了，请稍后再试');
            return;
        }

        setIsSearching(true);
        debouncedSearch(keyword);
    };

    const columns = [
        { title: '学号', dataIndex: 'studentNumber', key: 'studentNumber' },
        { title: '姓名', dataIndex: 'studentName', key: 'studentName' },
        {
            title: '评价等级',
            dataIndex: 'evaluation',
            key: 'evaluation',
            render: (text) => (
                <span style={{ color: text === 'A' ? 'red' : 'inherit' }}>
                    {text}
                </span>
            )
        },
        { title: '测评成绩', dataIndex: 'score', key: 'score' },
        { title: '提交时间', dataIndex: 'submittedTime', key: 'submittedTime', render: text => new Date(text).toLocaleString() },
    ];

    const rowClassName = (record) => {
        return record.evaluation === 'A级' || record.evaluation === 'B级' ? 'high-light' : '';
    };

    // 扇形图配置
    const pieOption = {
        title: {
            text: '不同等级所占比例',
            left: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [
            {
                name: '等级',
                type: 'pie',
                radius: '50%',
                data: Object.entries(statistics.levelDistribution).map(([name, value]) => ({ name, value })), // 使用统计数据
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    // 折线图配置
    const lineOption = {
        title: {
            text: '测评成绩和提交时间统计',
            left: 'center',
            textStyle: {
                fontSize: 18,
                fontWeight: 'bold',
                color: '#333'
            }
        },
        tooltip: {
            trigger: 'axis',
            formatter: (params) => {
                let tooltipHtml = '';
                params.forEach((param) => {
                    const value = param.value;
                    if (param.seriesName === '操作时间') {
                        // 如果是操作时间，直接显示提交时间
                        tooltipHtml += `${param.seriesName}: ${value}<br/>`;
                    } else {
                        // 其他数据保持原样
                        tooltipHtml += `${param.seriesName}: ${value}<br/>`;
                    }
                });
                return tooltipHtml;
            }
        },
        xAxis: {
            type: 'category',
            data: statistics.operationTimes.map(item => item.date), // 使用统计数据
            axisLabel: {
                color: '#666',
                fontSize: 12
            },
            axisLine: {
                lineStyle: {
                    color: '#999'
                }
            },
            
        },
        yAxis: [
            {
                type: 'value',
                name: '测评成绩',
                nameTextStyle: {
                    color: '#666',
                    fontSize: 12
                },
                axisLabel: {
                    color: '#666',
                    fontSize: 12
                },
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                }
            },
            {
                type: 'value',
                nameTextStyle: {
                    color: '#666',
                    fontSize: 12
                },
                axisLabel: {
                    color: '#666',
                    fontSize: 12
                },
                axisLine: {
                    lineStyle: {
                        color: '#999'
                    }
                }
            }
        ],
        series: [
            {
                name: '测评成绩',
                type: 'line',
                data: statistics.operationTimes.map(item => item.score), // 使用统计数据
                smooth: true, // 平滑曲线
                lineStyle: {
                    color: '#1890ff', // 线条颜色
                    width: 2
                },
                itemStyle: {
                    color: '#1890ff', // 数据点颜色
                    borderColor: '#fff',
                    borderWidth: 2
                },
                markPoint: {
                    data: [
                        { type: 'max', name: '最高分' },
                        { type: 'min', name: '最低分' }
                    ],
                    symbolSize: 60, // 标记大小
                    label: {
                        color: '#fff',
                        fontSize: 12
                    },
                    itemStyle: {
                        color: '#ff4d4f' // 标记颜色
                    }
                },
                markLine: {
                    data: [
                        { type: 'average', name: '平均分' }
                    ],
                    lineStyle: {
                        color: '#ff7a45', // 平均分线条颜色
                        width: 2,
                        type: 'dashed' // 虚线
                    },
                    label: {
                        color: '#ff7a45',
                        fontSize: 12
                    }
                }
            },
            {
                name: '提交时间',
                type: 'line',
                data: statistics.operationTimes.map(item => item.time), // 使用统计数据
                smooth: true, // 平滑曲线
                lineStyle: {
                    color: '#52c41a', // 线条颜色
                    width: 2
                },
                itemStyle: {
                    color: '#52c41a', // 数据点颜色
                    borderColor: '#fff',
                    borderWidth: 2
                },
                yAxisIndex: 1 // 使用第二个 Y 轴
            }
        ]
    };

    return (
        <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '50px' }}>
                <Card style={{ width: '48%' }}>
                    <ReactECharts option={pieOption} />
                </Card>
                <Card style={{ width: '48%' }}>
                    <ReactECharts option={lineOption} />
                </Card>
            </div>
            <Form form={searchForm} layout="inline" onFinish={handleSearch} className="mt-5">
                <FormItem name="keyword">
                    <Input
                        placeholder="请输入学号或评价等级进行搜索"
                        style={{ height: '40px' }}
                    />
                </FormItem>
                <FormItem>
                    <Button
                        type="primary"
                        htmlType="submit"
                        loading={isSearching}
                    >
                        搜索
                    </Button>
                </FormItem>
            </Form>
            <Table
                columns={columns}
                dataSource={filteredAssessments}
                rowKey="id"
                rowClassName={rowClassName}
            />
        </div>
    );
};

export default View_Inf;